package com.cyou.qb.front.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cyou.fz173.util.JacksonUtil;
import com.cyou.qb.common.domain.Active;
import com.cyou.qb.common.domain.ActiveRule;
import com.cyou.qb.common.domain.JiuGongGeEx;
import com.cyou.qb.common.domain.WinnerContract;
import com.cyou.qb.common.domain.WinnerEx;
import com.cyou.qb.common.domain.vo.DrawAward;
import com.cyou.qb.common.domain.vo.OtherDrawAward;
import com.cyou.qb.common.domain.vo.VirtualDrawAward;
import com.cyou.qb.common.service.ActivityService;
import com.cyou.qb.common.service.ConfigDisService;
import com.cyou.qb.common.service.WinnerService;
import com.cyou.qb.constants.Constants;
import com.cyou.qb.exception.DrawException;
import com.cyou.qb.face.entity.AddressInfo;
import com.cyou.qb.face.entity.GameInfo;
import com.cyou.qb.face.entity.NameValue;
import com.cyou.qb.face.entity.UserContact;
import com.cyou.qb.face.entity.UserInfo;
import com.cyou.qb.face.entity.VideoInfo;
import com.cyou.qb.face.exception.QbGetDataException;
import com.cyou.qb.face.service.GetGameInfoService;
import com.cyou.qb.face.service.PassportCheckService;
import com.cyou.qb.face.service.QbOperateService;
import com.cyou.qb.front.utils.PassportUtils;
import com.cyou.qb.front.vo.ActiveFragment;
import com.cyou.qb.service.DrawService;

@Controller
@RequestMapping(value = "/draw")
public class DrawController extends BaseController {
	@Resource(name = "ActivityServiceCacheImpl")
	private ActivityService activityService;

	@Resource(name = "QbGameImpl")
//	@Resource(name = "QbGameMock")
	private GetGameInfoService gameInfoService;

	@Resource(name = "QbPassportImpl")
//	@Resource(name = "QbPassportMock")
	private PassportCheckService passportCheckService;
	
	@Resource(name="QbOperateImpl")
//	@Resource(name="QbOperateMock")
	private QbOperateService qbOperateService;
	

	@Resource(name = "ConfigDisServiceCacheImpl")
	private ConfigDisService configDisService;

	@Autowired
	private DrawService drawService;

	@Resource(name = "WinnerServiceCacheImpl")
	private WinnerService winnerService;


	/**
	 * 活动抽奖页
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/toDraw")
	public String toDraw(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String activeId = request.getParameter("activeId");
		Assert.hasText(activeId, "活动不能为空");
		Assert.isTrue(NumberUtils.isDigits(activeId));
		Active active = activityService.findActivity(Integer.parseInt(activeId));
		Assert.notNull(active, "活动不存在");

		String gameCode = active.getGameCode();
		Assert.hasText(gameCode, "游戏数据不能为空");

		List<JiuGongGeEx> jiuGongGeExList = configDisService.findJiuGongGeExByActId(Integer.parseInt(activeId));
		jiuGongGeExList = JiuGongGeEx.fillEmptyPosition(jiuGongGeExList, Integer.parseInt(activeId));
		Assert.isTrue(jiuGongGeExList.size() == 8);
		List<WinnerEx> topWinnerList = winnerService.findTopWinnerByActive(Integer.parseInt(activeId),
				Constants.TOP_WINNER_SIZE);
		//		Assert.isTrue(dataList.rowCount()>0);

		boolean focus = false;
		if (PassportUtils.isLogin(request, response)) {
			focus = passportCheckService.isFocus(gameCode, PassportUtils.getUserId(request, response));
		}
		String rule = active.getRule();
		if (rule == null)
			rule = "[]";
		List<ActiveRule> ruleList = JacksonUtil.toCollection(rule, ArrayList.class, ActiveRule.class);
		int gCost = 0;
		for (ActiveRule activeRule : ruleList) {
			if(activeRule.getType().equals("4")){
				gCost=activeRule.getValue();
			}
		}
		List<VideoInfo> videoInfoList = gameInfoService.getGameVideoInfo(gameCode);
		List<NameValue> gameNews = gameInfoService.getGameNews(gameCode);
		GameInfo frontGameInfo = gameInfoService.getFrontGameInfo(gameCode);

		model.addAttribute("active",active);
		model.addAttribute("focus",focus);
		model.addAttribute("ruleList", ruleList);
		model.addAttribute("videoInfoList", videoInfoList);
		model.addAttribute("gameNews", gameNews);
		model.addAttribute("gCost", gCost);
		model.addAttribute("frontGameInfo",frontGameInfo);
		
		List<WinnerEx> topWinnerList1 = new ArrayList<WinnerEx>();

		//FIXME更改成适应的数量
		if(topWinnerList.size() > 3){
			int count = (topWinnerList.size()/3)*3;
			System.out.println(count);
			for(int i=0;i<count;i++){
				topWinnerList1.add(i, topWinnerList.get(i));
				model.addAttribute("topWinnerList", topWinnerList1);
			}
		}else{
			model.addAttribute("topWinnerList", topWinnerList);
		}
		int i = 0;
		for (JiuGongGeEx obj : jiuGongGeExList) {
			model.addAttribute("jiuGongGeEx" + i, obj);
			i++;
		}
		return "draw/draw";
	}

	/**
	 * ajax 校验用户是否登录
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/checkLogin")
	public String checkLogin(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String jsonp = request.getParameter("jsonpcallback");
		boolean isLogin = PassportUtils.isLogin(request, response);
		if (isLogin) {
			print(response,jsonp+"({'value':'"+1+"'})");
		} else {
			print(response,jsonp+"({'value':'"+0+"'})");
		}
		return null;
	}

	/**
	 * ajax 进行抽奖
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "/playDraw")
	public String playDraw(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String jsonp = request.getParameter("jsonpcallback");
		String activeId = request.getParameter("activeId");
		Assert.hasText(activeId, "活动不能为空");
		Assert.isTrue(NumberUtils.isDigits(activeId));
		Active active = activityService.findActivity(Integer.parseInt(activeId));
		Assert.notNull(active, "活动不存在");
		try {
			if(active.getEndTime().getTime()<System.currentTimeMillis() || active.getStatus() != 1){
				throw new DrawException(DrawException.ACTIVE_OVER,"活动已经结束了");
			}
			int uCenterId = PassportUtils.getUserId(request, response);
			UserInfo userInfo = passportCheckService.getUserInfo(uCenterId);
			DrawAward draw = drawService.draw(Integer.parseInt(activeId), uCenterId, userInfo.getUserPassport());
			List<JiuGongGeEx> jiuGongGeExList = configDisService.findJiuGongGeExByActId(Integer.parseInt(activeId));
			jiuGongGeExList=JiuGongGeEx.fillEmptyPosition(jiuGongGeExList, Integer.parseInt(activeId));
			JiuGongGeEx position = DrawAward.position(jiuGongGeExList, draw);
			//TODO json可能会更好
			String str="success:"+position.getPosition();
			if(draw==null){
				str+=":"+0;
			}else{
				str+=":"+draw.getAwardType();
				switch(Integer.parseInt(draw.getAwardType())){
					case 1:
						str+=":"+draw.getAwardName()+":"+draw.getWinnerId();
						UserContact contact = passportCheckService.getContact(uCenterId, userInfo.getUserPassport());
						String json=JacksonUtil.toJson(contact);
						str+=":#"+json;
						break;
					case 2:
						str+=":"+((VirtualDrawAward)draw).getAwardName();
						str+=":"+((VirtualDrawAward)draw).getCardNo();
						str+=":"+StringUtils.trimToEmpty(((VirtualDrawAward)draw).getCardPassword());
						break;
					case 3:
						str+=":"+((OtherDrawAward)draw).getPlusNum();
						break;
					case 4:
						str+=":"+((OtherDrawAward)draw).getPlusNum();
						break;
					default:
						throw new RuntimeException("不可识别的奖品类型:"+draw.getAwardType());
				}
			}
			print(response,buildJsonp(jsonp, str));
		} catch (NumberFormatException e) {
			print(response, buildJsonp(jsonp, "error:活动id必须是数字"));
			return null;
		} catch (QbGetDataException e) {
			e.printStackTrace();
			print(response, buildJsonp(jsonp, "error:系统通讯出错"));
		} catch (DrawException e) {
			e.printStackTrace();
			print(response, buildJsonp(jsonp, "DrawException:"+e.getERROR_CODE()) );
		} catch (Exception e) {
			e.printStackTrace();
			print(response, buildJsonp(jsonp, "error:系统出错了") );
		}
		return null;
	}

	private String buildJsonp(String jsonp, String str) {
		return jsonp+"({'value':'"+str+"'})";
	}

	private DrawException getQbGetDataException(int i) {
		DrawException drawException = new DrawException(i, "创建的异常："+i);
		return drawException;
	}

	private DrawAward getDraw(int i) {
		DrawAward ret;
			switch(i){
			case 1:
				ret = new DrawAward();
				ret.setAwardName("实物");
				ret.setAwardType("1");
				break;
			case 2:
				ret = new VirtualDrawAward();
				ret.setAwardName("点卡");
				ret.setAwardType("2");
				((VirtualDrawAward)ret).setCardNo("cardNo");
				 ((VirtualDrawAward)ret).setCardPassword("CardPassword");
				break;
			case 3:
				ret = new OtherDrawAward();
				ret.setAwardName("GB");
				ret.setAwardType("3");
				((OtherDrawAward)ret).setPlusNum(7);
				break;
			case 4:
				ret = new OtherDrawAward();
				ret.setAwardName("EXP");
				ret.setAwardType("4");
				((OtherDrawAward)ret).setPlusNum(7);
				break;
			default:
				throw new RuntimeException("不可识别的奖品类型:");
		}
		ret.setWinnerId(111);
		return ret;
	}

	/**
	 * ajax 获取片段
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "/getFragment")
	public String getFragment(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
		
			String jsonp = request.getParameter("jsonpcallback");
			ActiveFragment fragment = new ActiveFragment();
			String activeId = request.getParameter("activeId");
			String width = request.getParameter("width");
			String height = request.getParameter("height");
			String topWinner = request.getParameter("topWinner");
			
		try {
			Assert.hasText(activeId,"活动id不能为空");
			Assert.hasText(width,"碎片宽不能为空");
			Assert.hasText(height,"碎片高不能为空");
			Assert.hasText(topWinner,"是否有中奖名单不能为空");
			
			Assert.isTrue(NumberUtils.isDigits(activeId));
			Active active = activityService.findActivity(Integer.parseInt(activeId));
			Assert.notNull(active, "活动不存在");

			List<JiuGongGeEx> jiuGongGeExList = configDisService.findJiuGongGeExByActId(Integer.parseInt(activeId));
			jiuGongGeExList = JiuGongGeEx.fillEmptyPosition(jiuGongGeExList, Integer.parseInt(activeId));
			Assert.isTrue(jiuGongGeExList.size() == 8);
			if(Boolean.parseBoolean(topWinner)){
				List<WinnerEx> topWinnerList = winnerService.findTopWinnerByActive(Integer.parseInt(activeId),Constants.TOP_WINNER_SIZE);
				model.addAttribute("topWinnerList",topWinnerList);
				fragment.setTopWinnerList(topWinnerList);
			}

			String rule = active.getRule();
			if (rule == null)
				rule = "[]";
			List<ActiveRule> ruleList = JacksonUtil.toCollection(rule, ArrayList.class, ActiveRule.class);
			int gCost = 0;
			for (ActiveRule activeRule : ruleList) {
				if(activeRule.getType().equals("4")){
					gCost=activeRule.getValue();
				}
			}
			model.addAttribute("gCost" , gCost);
			fragment.setgCost(gCost+"");
			model.addAttribute(active);
			fragment.setActive(active);
			//fragment.setActiveIsOver(active.getActiveIsEnd());
//			model.addAttribute("ruleList", ruleList);
			
			int i = 0;
			for (JiuGongGeEx obj : jiuGongGeExList) {
				model.addAttribute("jiuGongGeEx" + i, obj);
				i++;
			}
			fragment.setJiuGongGeExList(jiuGongGeExList);
			boolean login = PassportUtils.isLogin(request, response);
			model.addAttribute("loginable",login);
			fragment.setLoginable(login);
			if(login){
				int uCenterId = PassportUtils.getUserId(request, response);
				UserInfo userInfo = passportCheckService.getUserInfo(uCenterId);
				String nickname= userInfo.getNickname();
				int userGB = qbOperateService.getUserGb(userInfo.getUserPassport());
				
				model.addAttribute("nickname", nickname);
				model.addAttribute("userGB", userGB);
				fragment.setNickname(nickname);
				fragment.setUserGB(userGB+"");
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.debug("ajax 抽奖碎片出错：",e);
			fragment.setError("系统出错");
			log.debug("ajax 抽奖碎片："+fragment.toJson());
			print(response,jsonp+"("+fragment.toJson()+")");
		}
		print(response,jsonp+"("+fragment.toJson()+")");
		log.debug("ajax 抽奖碎片："+fragment.toJson());
		System.out.println(jsonp+"("+fragment.toJson()+")");
		return null;
		
		
	}

	/**
	 * ajax 设置关注
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/setFocus")
	public String setFocus(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
		boolean isLogin = PassportUtils.isLogin(request, response);
		if (isLogin) {
			String gameCode = request.getParameter("gameCode");
			Assert.hasText(gameCode,"gameCode不能为空");
			passportCheckService.addGameFocus(gameCode, PassportUtils.getUserId(request, response));
			print(response, "1");
		} else {
			print(response, "0");
		}
		return null;
	}
	@RequestMapping(value = "/getUserContract")
	public String getUserContract(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			if(PassportUtils.isLogin(request, response)){
				int userId = PassportUtils.getUserId(request, response);
				UserInfo userInfo = passportCheckService.getUserInfo(userId);
				UserContact contact = passportCheckService.getContact(userId, userInfo.getUserPassport());
				String json=JacksonUtil.toJson(contact);
				print(response, json);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(value = "/setUserContract")
	public String setUserContract(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			String winnerId = request.getParameter("winnerId");
			String realName = request.getParameter("realName");
			String phone = request.getParameter("phone");
			String province = request.getParameter("province");
			String city = request.getParameter("city");
			String addressCode = request.getParameter("addressCode");
			String passport = request.getParameter("passport");
			if(addressCode.length()>6){
				addressCode=addressCode.substring(0,6);
			}
			String address = request.getParameter("address");
			String qq = request.getParameter("qq");

			Assert.hasText(realName);
			Assert.hasText(phone);
			Assert.hasText(province);
			Assert.hasText(city);
			Assert.hasText(addressCode);
			Assert.hasText(address);
			
			winnerId=StringUtils.trimToEmpty(winnerId);
			realName=StringUtils.trimToEmpty(realName);
			phone=StringUtils.trimToEmpty(phone);
			province=StringUtils.trimToEmpty(province);
			city=StringUtils.trimToEmpty(city);
			addressCode=StringUtils.trimToEmpty(addressCode);
			address=StringUtils.trimToEmpty(address);
			if(qq==null){
				qq="";
			}else{
				qq=qq.trim();
			}
			WinnerContract contract = new WinnerContract();
			contract.setWinnerId(Integer.parseInt(winnerId));
			contract.setRealName(realName);
			contract.setPhone(phone);
			contract.setProvince(province);
			contract.setCity(city);
			contract.setAddressCode(addressCode);
			contract.setAddress(province+" "+ city+" "+address);
			contract.setQq(qq);

			AddressInfo addressInfo = new AddressInfo();
			addressInfo.setDetailedAddress(address);
			addressInfo.setMobilephone(phone);
			addressInfo.setQqNum(qq);
			addressInfo.setUserTrueName(realName);
			winnerService.saveWinnerContract(contract);
			boolean flag = passportCheckService.updateAddress(Integer.parseInt(winnerId), addressInfo, passport);
			if(flag == false){
				new QbGetDataException("写入173失败");
			}
			print(response, "1");
		} catch (Exception e) {
			e.printStackTrace();
			print(response, "0");
		}
		return null;
	}

}
